package com.example.controller;

import cn.hutool.core.io.FileUtil;
import com.example.common.R;
import com.example.exception.RegisterException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${scfile.file}")
    private String basePath;

    @PostMapping("/upload")
    public R uploadFile(MultipartFile file) {
        // 将原来的文件名替换成 uuid
        String fileName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 创建一个目录对象
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            throw new RegisterException(e.getMessage(),101);
        }
        return R.success(fileName);
    }
    @GetMapping("/download")
    public R download(@RequestParam String name, HttpServletResponse response) {
        // 输入流 读文件
        byte[] bytes = FileUtil.readBytes(basePath + name);
        try {
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success("success");
    }
}
